const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

/**
 * 授权管理
 * @param {*} auth 权限
 * @param {*} content showModal 的内容提示
 */
const auth = (auth, content) => {
  return new Promise((resolve, reject) => {
    wx.getSetting({
      success: res => {
        if (!res.authSetting[auth]) {
          wx.authorize({
            scope: auth,
            success: () => {
              resolve(true)
            },
            fail: () => {
              wx.showModal({
                title: '提示',
                content: content,
                success: res => {
                  if(res.confirm){
                    wx.openSetting({
                      success: res => {
                        if (!res.authSetting[auth]) {
                          resolve(false)
                        } else {
                          resolve(true)
                        }
                      }
                    })
                  } else {
                    resolve(false)
                  }
                }
              })
            }
          })
        } else {
          resolve(true)
        }
      }
    })
  })
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

module.exports = {
  formatTime,
  auth
}